#include <sys/select.h>
#include <time.h>
#include <stdio.h>
#include "utils.h"

char utils_getchar_nonblocking() {
	fd_set descriptors;
	FD_ZERO(&descriptors);
	FD_SET(fileno(stdin), &descriptors);
	struct timeval timeout;
	timeout.tv_sec = 0;
	timeout.tv_usec = 0;

	char received = '\0';
	int select_status = select(fileno(stdin)+1, &descriptors, NULL, NULL, &timeout);
	if (select_status < 0) {
		perror("There was an error during the execution of the select command");
	} 
	else if (select_status > 0) {
		if (FD_ISSET(fileno(stdin), &descriptors)) {
			received = getchar();
		}
	}
	return received;
}

void utils_mssleep(size_t milisecs) {
	struct timespec req={0},rem={0};
	time_t sec=milisecs/1000;
	req.tv_sec=sec;
	req.tv_nsec=(milisecs - sec*1000)*1000000L;
	nanosleep(&req,&rem);
}

